package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/*
全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /*
    不允许插入重复的数据
    Duplicate entry '王五' for key 'employee.idx_username'
     */

    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //获取到异常信息
        String message = ex.getMessage();
        // 捕获到的异常是否包含Duplicate entry
        if (message.contains("Duplicate entry")){
            //根据空格进行截取
            String[] split = message.split(" ");
            //找到数组里面的2号元素，因为这个元素是动态的
            String username =  split[2];
            // "王五" + "已存在"
            String msg  = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);

        }else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }



    @ExceptionHandler
    public Result handlerException(BaseException e){
        log.info("错误：{}",e.getMessage());
        return Result.error(e.getMessage());

    }

}
